<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="100px">
      <el-form-item label="货品类型编号" prop="productTypeCode">
        <el-input
          v-model="queryParams.productTypeCode"
          placeholder="请输入货品类型编号"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="状态" prop="productTypeStatus">
        <el-select v-model="queryParams.productTypeStatus" placeholder="请选择状态" clearable>
          <el-option
            v-for="dict in dict.type.py_product_type"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['product:type:add']"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="el-icon-edit"
          size="mini"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['product:type:edit']"
        >修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['product:type:remove']"
        >删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
          v-hasPermi="['product:type:export']"
        >导出</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="typeList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="序号" align="center" prop="" >
        <template slot-scope="scope">
          {{ scope.$index + 1 }}
        </template>
      </el-table-column>
      <el-table-column label="货品类型编号" align="center" prop="productTypeCode" />
      <el-table-column label="货品类型名称" align="center" prop="productTypeName" />
      <el-table-column label="排序" align="center" prop="sort" />
      <el-table-column label="状态" align="center" prop="productTypeStatus">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.py_product_type" :value="scope.row.productTypeStatus"/>
        </template>
      </el-table-column>
      <el-table-column label="备注" align="center" prop="productTypeRemark" />
       <el-table-column label="操作人" align="center" prop="createBy" />
      <el-table-column label="操作时间" align="center"  >
        <template #default="scope">
          {{formatDateTime(scope.row.createTime)}}
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['product:type:edit']"
          >修改</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['product:type:remove']"
          >删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改货品类型对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="600px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="110px">
        <el-form-item label="上级分类" prop="parentId">
          <el-cascader
            v-model="selectedValue"
            :options="cascaderOptions"
            :props="cascaderProps"
            placeholder="请选择"
            @change="handleChange"
          />
        </el-form-item>

        <el-form-item label="货品类型编号" prop="productTypeCode">
          <el-input v-model="form.productTypeCode" placeholder="请输入货品类型编号"  readonly />
        </el-form-item>
        <el-form-item label="货品类型名称" prop="productTypeName">
          <el-input v-model="form.productTypeName" placeholder="请输入货品类型名称" />
        </el-form-item>
        <el-form-item label="排序" prop="sort">
          <el-input v-model="form.sort" placeholder="请输入排序" />
        </el-form-item>
        <el-form-item label="状态" prop="productTypeStatus">
          <el-select v-model="form.productTypeStatus" placeholder="请选择状态">
            <el-option
              v-for="dict in dict.type.py_product_type"
              :key="dict.value"
              :label="dict.label"
              :value="dict.value"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="备注" prop="productTypeRemark">
          <el-input v-model="form.productTypeRemark" type="textarea" placeholder="请输入内容" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { listType, getType, delType, addType, updateType,getCode } from "@/api/product/type";
import moment from "moment";
import { findSelect, findParent } from "@/api/product/type";
export default {
  name: "Type",
  dicts: ['py_product_type'],
  data() {
    return {
      //上级分类
      product: [],
      categoryParent:[],
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 货品类型表格数据
      typeList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        productTypeCode: null,
        productTypeStatus: null,
      },
      // 表单参数
      form: {
        number:undefined,
        codeId:undefined
      },
      // 表单校验
      rules: {
        productTypeCode: [
          { required: true, message: "货品类型编号不能为空", trigger: "blur" }
        ],
        productTypeName: [
          { required: true, message: "货品类型名称不能为空", trigger: "blur" }
        ],
      },
      selectedValue: [],
      cascaderOptions: [],
      cascaderProps: {
        value: undefined,
        label: undefined,
        children: undefined,
        checkStrictly: true // 允许非叶子节点的选项被选择
      }
    };
  },
  created() {
    this.getList();
    this.fetchItems();
    // this.selectCategoryParent();
  },
  methods: {
    /** 查询货品类型列表 */
    getList() {
      this.loading = true;
      listType(this.queryParams).then(response => {
        this.typeList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        productTypeId: null,
        productTypeCode: null,
        productTypeName: null,
        sort: null,
        parentId: null,
        productTypeStatus: null,
        createBy: null,
        createTime: null,
        updateBy: null,
        updateTime: null,
        productTypeRemark: null,
        isDelete: null
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.productTypeId)
      this.single = selection.length!==1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加货品类型";
      this.fetchItems();
       /** 获取编号*/
      getCode(12).then(response => {
        console.log(response);
        this.form.productTypeCode=response.sequence;
        this.form.number=response.number;
        this.form.codeId=response.codeId;
    });
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const productTypeId = row.productTypeId || this.ids
      getType(productTypeId).then(response => {
        this.form = response.data;
        this.open = true;
        this.title = "修改货品类型";
        this.$nextTick(() => {
          this.selectedValue = row.parentId ? [row.parentId] : [];
        });
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.productTypeId != null) {
            updateType(this.form).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addType(this.form).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const productTypeIds = row.productTypeId || this.ids;
      if (row.productTypeStatus == 1) {
        this.$modal.msgError("已启用的货品信息不能删除");
        return;
      } else {
        this.$modal.confirm('是否确认删除货品类型编号为"' + productTypeIds + '"的数据项？').then(function() {
        return delType(productTypeIds);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {});
      }
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('product/type/export', {
        ...this.queryParams
      }, `type_${new Date().getTime()}.xlsx`)
    },
     /**
     * 时间转换
     */
    formatDateTime(date){
      return moment(date).format("YYYY-MM-DD");
    },
    async fetchItems() {
      try {
        const response = await findSelect();
        console.log('Response from findSelect:', response);
        if (Array.isArray(response)) {
          this.cascaderOptions = await this.convertToCascaderOptions(response);
          console.log('Converted cascaderOptions:', this.cascaderOptions);
        } else {
          console.error('Expected an array, but got:', response);
        }
      } catch (error) {
        console.error('Error fetching items:', error);
      }
    },
    async convertToCascaderOptions(data) {
      if (!Array.isArray(data)) {
        console.error('Expected an array, but got:', data);
        return [];
      }

      // 创建一个映射，用于快速查找父项
      const itemMap = new Map(data.map(item => [item.productTypeCode, item]));
      // 创建一个数组，用于存储顶级项
      const topLevelItems = [];

      data.forEach(async (item) => {
        if (item.parentId === null) {
          // 顶级项直接添加到 topLevelItems
          topLevelItems.push(await this.createOption(item));
        } else {
          // 非顶级项，尝试找到其父项并添加到 children 数组
          const parentItem = itemMap.get(item.parentId);
          if (parentItem) {
            const childItem = await this.createOption(item);
            if (parentItem.children) {
              parentItem.children.push(childItem);
            } else {
              parentItem.children = [childItem];
            }
          }
        }
      });

      return topLevelItems;
    },
    async createOption(item) {
      return {
        value: item.productTypeCode,
        label: item.productTypeName,
        children: await this.fetchChildren(item.productTypeCode)
      };
    },
    async fetchChildren(parentId) {
      try {
        const response = await findParent(parentId);
        console.log('Response from findParent:', response);
        if (Array.isArray(response)) {
          return Promise.all(response.map(async (item) => {
            return {
              value: item.productTypeCode,
              label: item.productTypeName,
              children: await this.fetchChildren(item.productTypeCode)
            };
          }));
        } else {
          console.error('Expected an array, but got:', response);
          return [];
        }
      } catch (error) {
        console.error('Error fetching children:', error);
        return [];
      }
    },
    handleChange(value) {
      console.log('Selected:', value);
      const currentSelectedValue = value[value.length - 1];
      console.log('Current Selected:', currentSelectedValue);
      //alert(currentSelectedValue);
      this.form.parentId=currentSelectedValue;
    }
  }
};
</script>
<style>
select {
  width: 100%;
  padding: 8px;
  margin-top: 5px;
  border: 1px solid #ccc;
  border-radius: 4px;
  box-sizing: border-box;
}

option {
  padding: 5px;
}
</style>
